﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Utility;

namespace FrameWorkCore.IdentityServer4
{
    public static class IdentityServer4Service
    {
        public static void ConfigureIdentityServer4(this IServiceCollection services)
        {
            services.AddAuthentication(options =>
                   {
                       options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                       options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                   })
                   .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
                    {
                        options.Authority = "http://localhost:5001";//This is the identity of the server url
                        options.RequireHttpsMetadata = false;//
                        options.TokenValidationParameters = new TokenValidationParameters
                        {
                            ValidateAudience = false,
                            ValidateLifetime = true,
                            RequireExpirationTime = true,
                        };
                        options.Events = new JwtBearerEvents()
                        {
                            OnChallenge = context =>
                            {
                                context.HandleResponse();
                                context.Response.ContentType = "application/json";
                                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                                context.Response.WriteAsync(new
                                {
                                    Code = StatusCodes.Status401Unauthorized,
                                    Msg = "You have no authorization or token has failed! Please login again！"
                                }.ToJson());
                                return Task.FromResult(0);
                            }
                        };

                    });
        }
    }
}
